package com.ptsolusi.ceriacrudwicket.tool.dataproviders;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.IModel;

import com.ptsolusi.ceriacrudwicket.logic.CustomerLogic;
import com.ptsolusi.ceriacrudwicket.model.Customer;
import com.ptsolusi.ceriacrudwicket.tool.CeriacrudwicketApplication;
import com.ptsolusi.ceriacrudwicket.tool.models.DetachableCustomerModel;

public class CustomerDataProvider implements IDataProvider {
	
	private static final long serialVersionUID = 1L;
	private transient List<Customer> list = null;
	private transient CustomerLogic customerLogic = CeriacrudwicketApplication.get().getCustomerLogic();
	private static Logger log = Logger.getLogger(CustomerDataProvider.class);

	public CustomerDataProvider(){
		list = getItems();
		if(list==null)
			list = new ArrayList<Customer>();
		System.out.println("items size : "+list.size());
	}
	
	public CustomerDataProvider(String firstName){
		list = getItems(firstName);
		if(list==null)
			list = new ArrayList<Customer>();
		System.out.println("items size param : "+list.size());
	}
	
	private List<Customer> getItems(){
		return customerLogic.getAllCustomers();
	}
	
	private List<Customer> getItems(String firstName){
		return customerLogic.getCustomerByFirstName(firstName);
	}
	
	public void detach() {
		// TODO Auto-generated method stub
		
	}

	public Iterator<Customer> iterator(int first, int count) {
		try {
			List<Customer> slice = list.subList(first, first + count);
			return slice.iterator();
		}
		catch (Exception e) {
			e.printStackTrace();
			return Collections.EMPTY_LIST.iterator();
		}
	}

	public IModel model(Object object) {
		return new DetachableCustomerModel((Customer) object);
	}

	public int size() {
		if (list == null) {
			return 0;
    	}
		return list.size();
	}

}
